package com.xkstream.client.ui;

import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;

import com.xkstream.client.R;
import com.xkstream.client.application.Application;
import com.xkstream.client.base.AnimationListenerAdapter;
import com.xkstream.client.base.BaseActivity;
import com.xkstream.client.base.BaseData;
import com.xkstream.client.base.OnPageChangedListenerAdapter;
import com.xkstream.client.entity.ReceiveGift;
import com.xkstream.client.entity.User;
import com.xkstream.client.entity.kt.GainsData;
import com.xkstream.client.entity.kt.GiftRankingData;
import com.xkstream.client.presenter.kt.GainsRecorderContract;
import com.xkstream.client.presenter.kt.GainsRecorderPresenter;
import com.xkstream.client.ui.adapter.ContributionRankAdapter;
import com.xkstream.client.ui.adapter.CustomPagerAdapter;
import com.xkstream.client.ui.adapter.RewardAdapter;
import com.xkstream.client.ui.adapter.SelectMoneyAdapter;
import com.xkstream.client.utils.DeviceUtils;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindArray;
import butterknife.BindColor;
import butterknife.BindString;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.functions.BiFunction;

/**
 * Created by xiaoyi on 2017-9-28.
 */

public class GainsRecorderActivity extends BaseActivity<GainsRecorderContract.Presenter>
        implements GainsRecorderContract.View {
    @BindView(R.id.tvRight)
    TextView tvRight;
    @BindView(R.id.line)
    View line;
    @BindArray(R.array.money_type)
    String[] moneyTypes;
    @BindView(R.id.cover)
    View cover;
    @BindView(R.id.recycler_money)
    RecyclerView recyclerMoney;

    GridLayoutManager layoutManager;
    @BindView(R.id.headerBack)
    ImageView headerBack;
    @BindView(R.id.tv_gains)
    TextView tvGains;
    @BindView(R.id.tv_gains_count)
    TextView tvGainsCount;
    @BindView(R.id.tv_divient_count)
    TextView tvDivientCount;
    @BindView(R.id.tv_divient_rate)
    TextView tvDivientRate;
    @BindView(R.id.tv_gift_count)
    TextView tvGiftCount;
    @BindView(R.id.tv_gift_value)
    TextView tvGiftValue;
    @BindView(R.id.tabLeft)
    TextView tabLeft;
    @BindView(R.id.tabCenter)
    TextView tabCenter;
    @BindView(R.id.tabRight)
    TextView tabRight;

    @BindView(R.id.viewpager)
    ViewPager viewPager;

    @BindColor(R.color.white)
    int colorSelected;
    @BindColor(R.color.text_title)
    int colorUnselected;

    @BindString(R.string.gains_today)
    String gainsToday;
    @BindString(R.string.dividents_rate)
    String dividentsRate;

    private List<View> views = new ArrayList<>();


    @Override
    protected void initViews(Bundle savedInstanceState) {
        setContentView(R.layout.activity_gainsrecorder);
        ButterKnife.bind(this);
        setTitle(R.string.gains);
        initRightBtn();
        presenter = new GainsRecorderPresenter(this);
        fillViewPagerData();
        getGiftRanking("CNY");
        tvGains.setText(String.format(gainsToday, moneyTypes[0]));
    }

    private void initRightBtn() {
        tvRight.setText(moneyTypes[0]);
        tvRight.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.icon_drop_down, 0);
        tvRight.setCompoundDrawablePadding(DeviceUtils.dp2px(this, 2));
        layoutManager = new GridLayoutManager(this, 2);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerMoney.setLayoutManager(layoutManager);
        SelectMoneyAdapter adapter = new SelectMoneyAdapter(this, moneyTypes);
        recyclerMoney.setAdapter(adapter);
        adapter.setOnItemClickListener((v, p) -> {
            setSelectedIndex(0);
            tvRight.setText(moneyTypes[p]);
            getGiftRanking(moneyTypes[p]);
            tvGains.setText(String.format(gainsToday, moneyTypes[p]));
            hideSelectMoney();
        });


    }

    private void showSelectMoney() {
        recyclerMoney.setVisibility(View.VISIBLE);
        Animation anim = AnimationUtils.loadAnimation(this, R.anim.pw_top_in);
        recyclerMoney.setAnimation(anim);
        anim.setAnimationListener(new AnimationListenerAdapter() {
            @Override
            public void onAnimationStart(Animation animation) {
                super.onAnimationStart(animation);

                cover.setVisibility(View.VISIBLE);
            }
        });
        recyclerMoney.startAnimation(anim);
        cover.setOnClickListener((v) -> {
            hideSelectMoney();

        });
    }


    public void hideSelectMoney() {
        Animation anim = AnimationUtils.loadAnimation(this, R.anim.pw_top_out);
        recyclerMoney.setAnimation(anim);
        anim.setAnimationListener(new AnimationListenerAdapter() {
            @Override
            public void onAnimationStart(Animation animation) {
                super.onAnimationStart(animation);
                recyclerMoney.setVisibility(View.GONE);
                cover.setVisibility(View.GONE);
            }
        });
        recyclerMoney.startAnimation(anim);
    }

    @Override
    public void onBackPressed() {
        if (cover.getVisibility() == View.VISIBLE) {
            hideSelectMoney();
        } else {
            super.onBackPressed();
        }
    }


    @OnClick({R.id.tvRight, R.id.tabLeft, R.id.tabCenter, R.id.tabRight
            , R.id.headerBack, R.id.llReward})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tvRight:
                showSelectMoney();
                break;
            case R.id.tabLeft:
                setSelectedIndex(0);
                viewPager.setCurrentItem(0, true);
                break;
            case R.id.tabCenter:
                setSelectedIndex(1);
                viewPager.setCurrentItem(1, true);
                break;
            case R.id.tabRight:
                setSelectedIndex(2);
                viewPager.setCurrentItem(2, true);
                break;
            case R.id.headerBack:
                finish();
                break;
            case R.id.llReward:
                jumpToActivity(RewardActivity.class);
                break;
        }
    }

    private void setSelectedIndex(int index) {
        tabLeft.setBackgroundResource(index == 0 ? R.drawable.tab_left_selected
                : R.drawable.tab_left_unselected);
        tabLeft.setTextColor(index == 0 ? colorSelected : colorUnselected);
        tabCenter.setBackgroundResource(index == 1 ? R.drawable.tab_center_selected
                : R.drawable.tab_center_unselected);
        tabCenter.setTextColor(index == 1 ? colorSelected : colorUnselected);
        tabRight.setBackgroundResource(index == 2 ? R.drawable.tab_right_selected
                : R.drawable.tab_right_unselected);
        tabRight.setTextColor(index == 2 ? colorSelected : colorUnselected);
    }

    private void fillViewPagerData() {
        viewPager.removeAllViews();
        CustomPagerAdapter pagerAdapter = new CustomPagerAdapter(views);
        viewPager.setAdapter(pagerAdapter);
        viewPager.addOnPageChangeListener(new OnPageChangedListenerAdapter() {
            @Override
            public void onPageSelected(int position) {
                setSelectedIndex(position);
            }
        });
    }

    private View generateView(List<ReceiveGift> data) {
        RecyclerView recyclerView = new RecyclerView(this);
        ContributionRankAdapter adapter = new ContributionRankAdapter(this, data);
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        recyclerView.setAdapter(adapter);
        return recyclerView;
    }


    private void testData() {
        List<ReceiveGift> week = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            ReceiveGift gift = new ReceiveGift();
            gift.setNickname(String.format("扫黄%d队长", i));
            week.add(gift);
        }
        List<ReceiveGift> month = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            ReceiveGift gift = new ReceiveGift();
            gift.setNickname(String.format("少先队%d队长", i));
            month.add(gift);
        }
        List<ReceiveGift> totaly = new ArrayList<>();
        for (int i = 0; i < 8; i++) {
            ReceiveGift gift = new ReceiveGift();
            gift.setNickname(String.format("小虎队%d队长", i));
            totaly.add(gift);
        }
        views.add(generateView(week));
        views.add(generateView(month));
        views.add(generateView(totaly));


    }

    @Override
    public void showGiftRanking(BaseData<GiftRankingData> data) {
        fillRankingData(data.getData());
    }

    private void fillRankingData(GiftRankingData data) {
        if (data != null) {
            List<ReceiveGift> week = data.getWeek();
            List<ReceiveGift> month = data.getMonth();
            List<ReceiveGift> totaly = data.getTotal();
            views.clear();

            views.add(generateView(week));
            views.add(generateView(month));
            views.add(generateView(totaly));

            fillViewPagerData();
        }
    }

    @Override
    public void showError(@NotNull String message) {
        showTopTips(message);
    }

    @Override
    public void setPresenter(GainsRecorderContract.Presenter presenter) {
        this.presenter = presenter;
    }

    private void getGiftRanking(String type) {
        User user = Application.getUser();
        Map<String, Object> params = new HashMap<>();
        params.put("anchor_user_code", user.getUser_code());
        params.put("currency", type);
        presenter.getGainsData(params);
    }

    @Override
    public void showTodayGains(@NotNull BaseData<GainsData> t) {
        fillTodayGains(t.getData());
    }

    private void fillTodayGains(GainsData data) {
        if (data != null) {
            if (data.getGift_number_value()== null) return;
            tvGiftCount.setText(data.getGift_number_value().getGift_number());
            tvGiftValue.setText(data.getGift_number_value().getAsanchor_get_value());
            tvGainsCount.setText(data.getGift_number_value().getAnchor_channel_get_value());
            tvDivientRate.setText(String.format(dividentsRate,
                    data.getAnchor().getCut_ratio()));
            tvDivientCount.setText(data.getTotal().getTotal_value());

        }
    }


    @Override
    public void showGainsData(@NotNull GainsData t) {
        fillRankingData(t.getRanking());
        fillTodayGains(t);
    }
}
